package Cain.fb 
{
	import Cain.fb.event.Friend;
	import Cain.fb.event.GetAppFriends;
	import Cain.fb.event.GetFriendsEvent;
	import Cain.fb.event.GetUserEvent;
	import Cain.fb.event.PublishStreamEvent;
	import Cain.fb.event.User;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	/**
	 * 阿Cain的 FB API v1.22 2010.11.23
	 * @author cain in liontravel 2010
	 */
	public class Fb_API extends EventDispatcher
	{
		/**
		 * iframe模式下已登入
		 */
		static public const FB_IFRAME_LOGIN:String = "Fb_API_FB_IFRAME_LOGIN";
		/**
		 * 取回iframe模式下是否已登入
		 */
		static public const FB_IFRAME_LOGIN_CK:String = "Fb_API_FB_IFRAME_LOGIN_CK";
		/**
		 * 連線事件
		 */
		static public const FB_LINK:String = "Fb_API_FB_LINK";
		/**
		 * 取得SESSION 事件
		 */
		static public const onSESSION:String = "Fb_API_onSESSION";
		/**
		 * 登入事件
		 */
		static public const onLOGIN:String = "Fb_API_onLOGIN";
		/**
		 * Graph API 回傳事件
		 */
		static public const onRESPONSE:String = "Fb_API_onRESPONSE";
		/**
		 * UI 回傳事件
		 */
		static public const onRESPONSE_UI:String = "Fb_API_onRESPONSE_UI";
		
		private var api:String = "";
		public var session:Object;
		public var data:String;
		public var obData:Object;
		private var win_id:String;
		/**
		 * user頭像路徑
		 * @param	_ob user資料物件
		 * @param	_large 圖片規格 150x150 or 50x50
		 * @return 路徑
		 */
		static public function getPicture(_uid:int,_large:Boolean = true):String
		{
			var _url:String;
			_url = "http://graph.facebook.com/" + _uid + "/picture";
			if (_large) 
			{
				_url += "?type=large";
			}
			return _url;
		}
		/**
		 * 初始化
		 * @param	_api api_key
		 */
		public function Fb_API(_api:String) 
		{
			trace("阿Cain的FB API v1.22啟動...")
			api = _api;
			if(ExternalInterface.available) 
			{
				win_id = ExternalInterface.objectID;
			}
		}
		/**
		 * 登入
		 * 非同步發出 onLOGIN 事件
		 * 回傳data 成功為 true
		 */
		public function login():void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("onLogin", onLogin);
				ExternalInterface.call(Javascript.login,api,win_id);
			}
		}
		
		/**
		 * 連線FB
		 * 非同步 連線觸發 FB_LINK 事件
		 * 回傳 obData 發出  
		 * connected 為成功 onRESPONSE 事件
		 */
		public function fb_link():void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("re_data", re_data);
				ExternalInterface.call(Javascript.fb_link,api,win_id);
			}
		}
		public function getSession():void
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("onSession", onSession);
				ExternalInterface.call(Javascript.fb_session,win_id);
			}
		}
		/**
		 * 導向登入頁面
		 * @param	_client_id api的id
		 * @param	_app_url 導向網址
		 */
		static public function iframe_login_location(_client_id:String,_app_url:String):void 
		{
			navigateToURL(new URLRequest("https://graph.facebook.com/oauth/authorize?client_id=" + _client_id + "&redirect_uri=" + _app_url+"&scope=user_photos,user_videos,publish_stream,email"),"_top");
		}
		/**
		 * 呼叫 Graph API
		 * 取回obData 發出 onRESPONSE 事件
		 * @param	_call 傳入指令
		 */
		public function graphAPI(_call:Object):void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("response", response);
				ExternalInterface.call(Javascript.api,_call,win_id);
			}
		}
		/**
		 * 取得使用者資料
		 * 回傳GetUserEvent事件
		 * @param	_name user name ,預設為取回自己
		 */
		public function getUser(_name:* = ""):void
		{
			if (_name == "") 
			{
				_name = "/me";
			}
			addEventListener(onRESPONSE, onGetUser);
			graphAPI(_name);
		}
		/**
		 * FB.UI API
		 * 回傳onRESPONSE_UI事件 obData回傳值
		 */
		public function ui(_call:Object):void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("response_ui", response_ui);
				ExternalInterface.call(Javascript.ui,_call,win_id);
			}
		}
		/**
		 * 使用FBML語言,dialog跳出視窗,使用時flash外掛 wmode 請設為 Opaque
		 * 回傳onRESPONSE_UI事件 obData回傳值
		 * @param	_fbml FBML語法
		 * @param	_width 寬
		 * @param	_height 高
		 */
		public function FBML(_fbml:String,_width:int = 100,_height:int=50):void 
		{
			ui( { method: "fbml.dialog", fbml: _fbml ,width: _width,  height: _height} );
		}
		/**
		 * 取回user資料
		 * @param	e
		 */
		private function onGetUser(e:Event):void 
		{
			removeEventListener(onRESPONSE, onGetUser);
			var _event:GetUserEvent = new GetUserEvent();
			_event.user = new User(obData);
			dispatchEvent(_event);
		}
		/**
		 * 取得朋友資料
		 * 回傳GetFriendsEvent事件
		 */
		public function getFriends():void 
		{
			addEventListener(onRESPONSE, onGetFriends);
			graphAPI("/me/friends");
		}
		/**
		 * 發送訊息
		 * 發送完成回傳PublishStreamEvent事件
		 * @param	_messageOb 訊息內容
		 */
		public function publishStream(_messageOb:PublishMessage):void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("rePublish_stream", rePublish_stream);
				ExternalInterface.call(Javascript.publish_stream,_messageOb.message,win_id);
			}
		}
		/**
		 * 取消授權
		 */
		public function disconnect():void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.call(Javascript.disconnect);
			}
		}
		/**
		 * 驗證是否已在iframe狀態下login 驗證完發出 FB_API.FB_IFRAME_LOGIN_CK 事件
		 * 你可以檢查obData為回傳參數,其中的的fb_sig_added屬性1為登入0為未登入
		 */
		public function iframe_login_ck():void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.addCallback("re_iframe_login", re_iframe_login);
				ExternalInterface.call(Javascript.iframe_login_ck,api,win_id);
			}
		}
		private var app_id:String;
		private var app_url:String;
		/**
		 * 已iframe方法登入 登入後發出 FB_API.FB_IFRAME_LOGIN 事件
		 * @param	_app_id app id
		 * @param	_app_url 轉回網址
		 */
		public function iframe_login(_app_id:String,_app_url:String):void 
		{
			app_id = _app_id;
			app_url = _app_url;
			addEventListener(FB_IFRAME_LOGIN_CK,iframe_login_ckok);
			iframe_login_ck();
		}
		/**
		 * 按下讚(old api)
		 * @param	_post_id 文章序號
		 */
		public function likes(_post_id:String):void 
		{
			if(ExternalInterface.available) 
			{
				graphAPI( { method: "stream.addLike",post_id: _post_id } );
				//ExternalInterface.call(Javascript.postLike,_post_id);
			}
		}
		/**
		 * 發佈訊息
		 * 回覆onRESPONSE事件,obData違反回資料
		 * @param	_arr 好友uid陣列
		 * @param	_str 訊息
		 * @param	_type 發文類別,預設為user_to_user 另一種為 app_to_user 
		 */
		public function sentMessage(_arr:Array,_str:String,_type:String="user_to_user"):void 
		{
			if(ExternalInterface.available) 
			{
				var _fids:String = "";
				for each (var _uid:* in _arr) 
				{
					_fids += String(_uid) + ",";
				}
				_fids = _fids.slice(0, -1);
				var _ob:Object = 
				{
					to_uds:	      _fids,
					notification: _str,
					type:		  _type
				};
				ExternalInterface.call(Javascript.api,_ob,win_id);
			}
		}
		/**
		 * 刪除發文 測試版
		 * @param	_postId 文章編號
		 */
		public function delPost(_postId:String):void 
		{
			if(ExternalInterface.available) 
			{
				ExternalInterface.call(Javascript.delPost,_postId,win_id);
			}
		}
		/**
		 * 取得有註冊此app的朋友(old api)
		 * 非同步返回 GetAppFriends.RESPONSE 事件
		 * 你可以取得事件的 uidArr 屬性
		 */
		public function getFriendsOnApp():void 
		{
			addEventListener(onRESPONSE, onFriendsOnApp);
			graphAPI( { method: "friends.getAppUsers" } );
		}
		private function onFriendsOnApp(e:Event):void 
		{
			removeEventListener(onRESPONSE, onFriendsOnApp);
			var _event:GetAppFriends = new GetAppFriends();
			_event.uidArr = obData as Array;
			dispatchEvent(_event);
		}
		private function iframe_login_ckok(e:Event):void 
		{
			removeEventListener(FB_IFRAME_LOGIN_CK, iframe_login_ckok);
			if (obData.fb_sig_added == "0") 
			{
				Fb_API.iframe_login_location(app_id, app_url);
			}else 
			{
				addEventListener(FB_LINK, onFB_LINK);
				fb_link();
			}
		}
		
		private function onFB_LINK(e:Event):void 
		{
			removeEventListener(Fb_API.FB_LINK, onFB_LINK);
			addEventListener(onSESSION, onSESSIONre);
			getSession();
		}
		private function onSESSIONre(e:Event):void 
		{
			removeEventListener(onSESSION, onSESSIONre);
			dispatchEvent(new Event(FB_IFRAME_LOGIN));
		}
		/**
		 * 返回是否認證
		 * @param	_str
		 */
		private function re_iframe_login(_ob:Object):void
		{
			obData = _ob;
			dispatchEvent(new Event(FB_IFRAME_LOGIN_CK));
		}
		/**
		 * 發送完成回傳訊息
		 */
		private function rePublish_stream(_ob:Object):void
		{
			var _event:PublishStreamEvent = new PublishStreamEvent();
			_event.success = Boolean(_ob.success);
			if (_event.success) 
			{
				_event.id = _ob.id;
			}else 
			{
				_event.error = _ob.error;
			}
			dispatchEvent(_event);
		}
		/**
		 * 取回朋友資料
		 * @param	e
		 */
		private function onGetFriends(e:Event):void 
		{
			removeEventListener(onRESPONSE, onGetFriends);
			var _event:GetFriendsEvent = new GetFriendsEvent();
			for each (var _ob:Object in obData.data) 
			{
				var _friend:Friend = new Friend(_ob.name, _ob.id);
				_event.data.push(_friend);
			}
			dispatchEvent(_event);
		}
		private function response(_ob:Object):void
		{
			obData = _ob;
			dispatchEvent(new Event(onRESPONSE));
		}
		private function response_ui(_ob:Object):void
		{
			obData = _ob;
			dispatchEvent(new Event(onRESPONSE_UI));
		}
		private function onLogin(_str:String):void
		{
			if (_str) 
			{
				data = "true";
			}else 
			{
				data = "false";
			}
			dispatchEvent(new Event(onLOGIN));
		}
		private function onSession(_ob:Object):void
		{
			obData = _ob;
			session = _ob;
			dispatchEvent(new Event(onSESSION));
		}
		private function re_data(_str:String):void
		{
			data = _str;
			dispatchEvent(new Event(FB_LINK));
		}
	}

}